package bs.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import bs.anno.LoginLogger;
import bs.entity.Permission;
import bs.entity.Role;
import bs.entity.User;
import bs.service.UserService;
import bs.util.ResponseUtil;
import bs.util.ResultMessage;

/**
 * 
 * UserController:
 *
 * @author 姜治昊
 * @time 2017年11月20日 上午10:15:16
 */
@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 认证登录
	 * @param user
	 */
	@LoginLogger
	@RequestMapping(value="login", method=RequestMethod.POST)
	public void authenticate(User user, HttpServletRequest request, HttpServletResponse response) {
		User u = userService.authenticate(user);
		HttpSession session = request.getSession();
		session.setAttribute("LOGIN_USER", u);
		session.setAttribute("PERMISSION_URLS", getPermissions(u));
		Object oldUrl = session.getAttribute("REQUEST_URL_BEFORE_LOGIN");
		if(null != oldUrl) {
			//跳转oldUrl界面
		}
		//main界面
		ResponseUtil.write(response, JSONObject.fromObject(ResultMessage.createSuccessResultMessage()));
	}
	
	/**
	 * 工具方法：将权限信息放在Session中
	 */
	private String[] getPermissions(User user) {
		List<Role> roles = user.getRoles();
		if(null != roles && roles.size() > 0) {
			for(Role role : roles) {
				List<Permission> permissions = role.getPermissions();
				String[] urls = new String[permissions.size()];
				if(null != permissions && permissions.size() > 0) {
					for(int i=0;i<permissions.size();i++) {
						urls[i] = permissions.get(i).getPermissionUrl();
					}
					return urls;
				}
			}
		}
		return null;
	}
	
}
